<template>
  <a-card title="网点查询" :bordered="false" class="condition-card">
    <div class="condition-row">
      <div class="condition-col flex align-center">
        <a-input allow-clear placeholder="请输入网点名称" v-model:value="conditionState.name"></a-input>
        <a-button class="ml-12" type="primary" :loading="searchLoading" @click="handleSearch">查询</a-button>
      </div>
    </div>
  </a-card>
  <a-card title="网点列表" :bordered="false" class="result-card mt-20">
    <template #extra>
      <a-button type="primary" @click="handlePopCreateModal">添加网点</a-button>
    </template>
    <a-table :columns="columns" :data-source="shopList" :pagination="false" :scroll="{y: 'calc(100vh - 405px)'}">
      <template #bodyCell="{record, column}">
        <template v-if="column.dataIndex === 'time'">
          <span v-if="record.allDay !== '1'">{{ record.beginTime }}-{{ record.endTime }}</span>
          <div class="tag primary-tag" v-else>24H</div>
        </template>
        <template v-if="column.dataIndex === 'option'">
          <a-button type="link" @click="handlePopEditModal(record)">
            <i class="iconfont icon-bianji"></i>
          </a-button>
          <a-popconfirm
              title="确定要删除吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelRecord(record)">
            <a-button class="ml-12" type="link" danger>
              <i class="iconfont icon-shanchu"></i>
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <div class="pagination-content flex justify-end">
      <a-pagination v-model:current="conditionState.page" show-quick-jumper show-size-changer
                    :show-total="total => `共 ${total} 条`" :total="total" v-model:pageSize="conditionState.size"
                    @change="handlePageChange"/>
    </div>
  </a-card>
  <a-modal :width="720" :title="editMode ? '编辑网点信息' : '添加网点信息'" v-model:visible="modalVisible"
           :confirmLoading="saveLoading" @ok="handleSave">
    <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        ref="shopForm">
      <a-row>
        <a-col :span="11">
          <a-form-item
              label="网点名称"
              name="wdname">
            <a-input v-model:value="formState.wdname" placeholder="请输入网点名称"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="2">
          <a-form-item
              label="选择商户"
              name="userName">
            <a-select v-model:value="formState.userName" placeholder="请选择商户">
              <a-select-option v-for="item in busUserList" :value="item.userName" :key="item.userName">{{item.nickName || item.userName}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="11">
          <a-form-item
              label="商户联系人手机号"
              name="phone">
            <a-input v-model:value="formState.phone" placeholder="请输入商户联系人手机号" :maxlength="11"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="2">
          <a-form-item
              label="网点地址"
              name="wdaddress">
            <div class="flex">
              <a-input v-model:value="formState.wdaddress" placeholder="请输入网点地址"></a-input>
              <a-button style="margin-left: 12px;" type="link" @click="handlePopMapModal">
                <i class="iconfont icon-weizhi"></i>
              </a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="7">
          <a-form-item
              label="洗车前几分钟"
              name="phone">
            <a-input-number v-model:value="formState.time_qian" placeholder="洗车前几分钟" :min="0" :max="999" ></a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="7" :offset="1">
          <a-form-item
              :label="`前${formState.time_qian}分钟每分钟多少钱`"
              name="phone">
            <a-input-number v-model:value="formState.time_qian_yuan" placeholder="每分钟多少钱" :min="0" :max="999" ></a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8" :offset="1">
          <a-form-item
              :label="`超过${formState.time_qian}分钟每分钟多少钱`"
              name="phone">
            <a-input-number v-model:value="formState.time_hou_yuan" placeholder="每分钟多少钱" :min="0" :max="999" ></a-input-number>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="11">
          <a-form-item
              label="网点描述"
              name="wddetail">
            <a-input v-model:value="formState.wddetail" placeholder="请输入网点描述"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="2">
          <a-form-item
              label="24小时营业">
            <a-select v-model:value="formState.allDay">
              <a-select-option value="1">是</a-select-option>
              <a-select-option value="0">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="11">
          <a-form-item
              label="营业时间">
            <a-time-picker v-model:value="formState.beginTime" placeholder="开始时间" format="HH:mm:ss"
                           value-format="HH:mm:ss"/>
            <span>&nbsp;&nbsp;-&nbsp;&nbsp;</span>
            <a-time-picker v-model:value="formState.endTime" placeholder="结束时间" format="HH:mm:ss"
                           value-format="HH:mm:ss"/>
          </a-form-item>
        </a-col>
        <a-col :span="11" :offset="2">
          <a-form-item
              label="营业状态">
            <a-select v-model:value="formState.yingyestate">
              <a-select-option value="营业中">营业中</a-select-option>
              <a-select-option value="休息">休息</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
  <a-modal :width="1200" v-model:visible="mapModalVisible" title="网点位置" @ok="handleConfirmPos">
    <div class="map-container" id="map"></div>
  </a-modal>
</template>

<script setup lang="ts">
import {nextTick, reactive, ref} from "vue";
import api from '../../api/merchant'
import userApi from '../../api/users'
import {ShopItem, UserItem} from '../../types/common'
import {UserTypesObj} from '../../common/constants'
import {uuid} from '../../common/utils'
import {message} from "ant-design-vue";

const modalVisible = ref<boolean>(false)
const editMode = ref<boolean>(false)
const defFormState = {
  "id": 0,
  "allDay": "1",
  "beginTime": "",
  "endTime": "",
  "latitude": "",
  "longitude": "",
  "phone": "",
  "time_hou_yuan": 0,
  "time_qian": 0,
  "time_qian_yuan": 0,
  "userName": undefined,
  "wdCode": "",
  "wdaddress": "",
  "wddetail": "",
  "wdimg": "",
  "wdname": "",
  "yingyestate": "营业中",// 休息
  "zuidixiaofei": 0,
  "zuigaoxiaofei": 0
}
const currentFormItem = ref()
const formState = ref({...defFormState})
const shopForm = ref()
const rules = {
  wdname: [
    {required: true, trigger: 'blur', message: '请输入网点名称'},
  ],
  wdaddress: [
    {required: true, trigger: 'blur', message: '请输入网点地址'},
  ],
  userName: [
    {required: true, trigger: 'blur', message: '请选择商户'},
  ],
  phone: [
    {required: true, trigger: 'blur', message: '请输入商户联系人手机号'},
  ],
}
const mapModalVisible = ref(false)
const selectPos = {
  lng: 0,
  lat: 0,
  address: ''
}
let map: window.google.maps.Map;
let Map, geocoder, marker, AdvancedMarkerView
(async () => {
  const mpl = await window.google.maps.importLibrary("maps") as window.google.maps.MapsLibrary;
  geocoder = new window.google.maps.Geocoder();
  const ml = await window.google.maps.importLibrary("marker") as window.google.maps.MarkerLibrary;
  Map = mpl.Map
  AdvancedMarkerView = ml.AdvancedMarkerView
})()

async function initMap(): Promise<void> {
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: {lat: 3.149064822131411, lng: 101.69365882873535},
    zoom: 14,
  });
  map.addListener('click', (e) => {
    const lat = e.latLng.lat()
    const lng = e.latLng.lng()
    console.log('mapclick', lng, lat)
    selectPos.lng = lng
    selectPos.lat = lat
    const location = {lng, lat}
    if (marker) {
      marker.setMap(null)
    }
    marker = new window.google.maps.Marker({
      map: map,
      position: location,
    });
    geocoder.geocode({location})
        .then((response) => {
          if (response.results[0]) {
            selectPos.address = response.results[0].formatted_address
          }
        })
  })
}
const busUserList = ref<UserItem[]>([])
const getBusUserList = async () => {
  busUserList.value = []
  try {
    const res = await userApi.getList({
      userName: '',
      userType: UserTypesObj.bus.code,
      page: 0,
      size: 999,
    })
    if (res.content) {
      if (res.content.content && res.content.content.length) {
        busUserList.value = res.content.content
      }
    }
  } catch(e: any) {
  }
}
getBusUserList()
const searchLoading = ref<boolean>(false)
const saveLoading = ref<boolean>(false)
const conditionState = reactive({
  name: '',
  page: 1,
  size: 10,
})
const total = ref<number>(0)
const shopList = ref<ShopItem[]>([])
const columns = [
  {
    dataIndex: 'wdCode',
    key: 'wdCode',
    title: '网点编号',
  },
  {
    dataIndex: 'wdname',
    key: 'wdname',
    title: '网点名称',
  }, {
    dataIndex: 'wdaddress',
    key: 'wdaddress',
    title: '网点地址',
  }, {
    dataIndex: 'time',
    key: 'time',
    title: '营业时间',
  }, {
    dataIndex: 'userName',
    key: 'userName',
    title: '商户',
  }, {
    dataIndex: 'wddetail',
    key: 'wddetail',
    title: '网点描述',
  }, {
    dataIndex: 'option',
    key: 'option',
    title: '操作',
  },
]
const getPageData = async () => {
  searchLoading.value = true
  shopList.value = []
  try {
    const res = await api.getList({
      name: conditionState.name || '',
      page: conditionState.page - 1,
      size: conditionState.size,
    })
    searchLoading.value = false
    if (res.content) {
      total.value = res.content.total || 0
      if (res.content.content && res.content.content.length) {
        shopList.value = res.content.content
      }
    }
  } catch (e: any) {
    searchLoading.value = false
  }

}
const handleSearch = () => {
  conditionState.page = 1
  total.value = 0
  getPageData()
}
const handlePageChange = (page: number, pageSize: number) => {
  if (pageSize !== conditionState.size) {
    conditionState.page = 1
  }
  getPageData()
}
handleSearch()
const handleSave = async () => {
  try {
    await shopForm.value.validateFields()
    console.log('formState', formState.value)
    if (formState.value.allDay === '0' && (!formState.value.beginTime || !formState.value.endTime)) {
      message.warning('请设置营业开始结束时间')
      return
    }
    saveLoading.value = true
    let res
    if (!editMode.value) {
      res = await api.create(formState.value)
    } else {
      res = await api.edit(formState.value)
    }
    saveLoading.value = false
    if (res.success) {
      if (!editMode.value) {
        message.success('网点添加成功')
        handleSearch()
      } else {
        message.success('网点修改成功')
        Object.assign(currentFormItem.value, formState.value)
      }
      modalVisible.value = false
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  } catch (e) {
    saveLoading.value = false
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
const handlePopCreateModal = () => {
  formState.value = {...defFormState}
  formState.value.wdCode = uuid(6)
  editMode.value = false;
  modalVisible.value = true
  nextTick(() => {
    shopForm.value.clearValidate()
  })
}
const handlePopEditModal = (item: any) => {
  currentFormItem.value = item
  Object.assign(formState.value, item)
  editMode.value = true;
  modalVisible.value = true
  nextTick(() => {
    shopForm.value.clearValidate()
  })
}
const handleDelRecord = async (item: any) => {
  try {
    const res = await api.del(item.id)
    if (res.success) {
      message.success('删除成功')
      handleSearch()
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  } catch (e) {
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
const handlePopMapModal = () => {
  mapModalVisible.value = true
  nextTick(async () => {
    await initMap()
    if (formState.value.longitude && formState.value.latitude) {
      const position = {lat: parseFloat(formState.value.latitude), lng: parseFloat(formState.value.longitude)};
      map.setCenter(position)
      marker = new window.google.maps.Marker({
        map,
        position: position,
      });
    } else {
      marker = null
    }
  })
}
const handleConfirmPos = () => {
  if (selectPos.lng && selectPos.lat) {
    formState.value.longitude = selectPos.lng
    formState.value.latitude = selectPos.lat
    formState.value.wdaddress = selectPos.address
  }
  mapModalVisible.value = false
}
</script>

<style scoped lang="less">
.map-container {
  position: relative;
  width: 1100px;
  height: 500px;
}
.ant-btn-link{
  padding: 0;
}
.ant-input-number{
  width: 100%;
}
</style>
